<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />

    <title>json-to-show</title>
    <style>
        
        table{border-collapse:collapse;margin:10px;}
        th,td{border:1px solid #000;}
        th{ background:#eee;}
        
    </style>
        
    <!-- Site CSS -->
    <link href="http://cdn.bootcss.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet">
    <link href="http://cdn.bootcss.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
    <!--<link href="http://static.bootcss.com/www/assets/css/site.min.css?v5" rel="stylesheet">-->
    
    <!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!--[if lt IE 9]>
      <script src="/assets/js/html5shiv.min.js?v=1f65f1e951"></script>
      <script src="/assets/js/respond.min.js?v=1f65f1e951"></script>
    <![endif]-->
    
</head>
<body>
 <div class="container">
       <h2>json-to-show</h2>
   
    <div class="row">
        <div class="col-sm-12">
            <textarea id="text" class="form-control" rows="10">{
            "a":1,
            "b":[{"a":"1","b":"2"},{"a":"1","b":"2"}],
            "c":[1,3,"ww"],
            "d":{
                "a":1,
                "b":[{"a":"1","b":"2"},{"a":"1","b":"2"}],
                "c":[1,3,"ww"],
                "d":null,
                "e":{
                    "a":1,
                    "b":[{"a":"1","b":"2"},{"a":"1","b":"2"}],
                    "c":[1,3,"ww"],
                    "d":{
                        "a":1,
                        "b":[{"a":"1","b":"2"},{"a":"1","b":"2"}],
                        "c":[1,3,"ww"],
                        "d":null
                        }
                    }
                }
            } {
            "a":1,
            "b":[{"a":"1","b":"2"},{"a":"1","b":"2"}],
            "c":[1,3,"ww"],
            "d":{
                "a":1,
                "b":[{"a":"1","b":"2"},{"a":"1","b":"2"}],
                "c":[1,3,"ww"],
                "d":null,
                "e":{
                    "a":1,
                    "b":[{"a":"1","b":"2"},{"a":"1","b":"2"}],
                    "c":[1,3,"ww"],
                    "d":{
                        "a":1,
                        "b":[{"a":"1","b":"2"},{"a":"1","b":"2"}],
                        "c":[1,3,"ww"],
                        "d":null
                        }
                    }
                }
            } {
            "a":1,
            "b":[{"a":"1","b":"2"},{"a":"1","b":"2"}],
            "c":[1,3,"ww"],
            "d":{
                "a":1,
                "b":[{"a":"1","b":"2"},{"a":"1","b":"2"}],
                "c":[1,3,"ww"],
                "d":null,
                "e":{
                    "a":1,
                    "b":[{"a":"1","b":"2"},{"a":"1","b":"2"}],
                    "c":[1,3,"ww"],
                    "d":{
                        "a":1,
                        "b":[{"a":"1","b":"2"},{"a":"1","b":"2"}],
                        "c":[1,3,"ww"],
                        "d":null
                        }
                    }
                }
            }</textarea>
        </div>
    </div>
     <div class="row">
        <div class="col-sm-12">
            <input type="text" class="form-control" value="a.b" id="expr"/>
        </div>
    </div>
    <div class="row">
        <div class="col-sm-12">
          <label><input id="merge" type="checkbox" /> 合并多个json </label><br/>
           <button id="btn" class="btn btn-primary"  >转</button>
          
        </div>
    </div>
    
       <div class="row">
        <div class="col-sm-12">
             <!--<textarea id="show2" class="form-control" rows="10"></textarea>-->
             <div id="show"></div>
        </div>
    </div>
   
   <hr>
  
   
 </div>

   
       <!-- Bootstrap core JavaScript
    ================================================== -->
    <!-- Placed at the end of the document so the pages load faster -->
    <script src="http://cdn.bootcss.com/jquery/1.11.1/jquery.min.js"></script>
    <script src="http://cdn.bootcss.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
   <script type="text/javascript" src="moment.js"></script>
   <script type="text/JavaScript">
        function log(w){
           // console.log.apply(this,arguments);
             console.log(w);
        }
        String.prototype.convertTime = function (){
           return this.replace(/\d{13}/ig,function(ts){
              return '['+ moment(parseInt(ts)).zone('-0500').format('YYYY-MM-DD HH:mm:ss') + ']';
            });
        };
        
        function addShell(val,shell,attr){
            if(attr){}else{
                attr='';
            }
            return '<'+shell+' '+attr+'>'+val+'</'+shell+'>';
        }
        
        function filterKeyValue(key,val){
            if(/[Tt]ime$/ig.test(key) && parseInt(val) >0 ){
                return moment(parseInt(val)).zone('-0500').format('YYYY-MM-DD HH:mm:ss') ;
            }
            return val;
        }
        function toShow(v,f){
            var html = '';
            if($.isPlainObject(v)){
                 log('isPlainObject');
                //get a obj type
                if(f == undefined){
                    $.each(v,function(key,val){
                        log(val);
                        html+=addShell(addShell(key,'th','valign="top"')+addShell(toShow(filterKeyValue(key,val)),'td'),'tr');
                    });
 
                    html=addShell(html,'table');
                }else if(f == 'tr'){//one row
                    $.each(v,function(e,i){
                        html+=addShell(toShow(filterKeyValue(e,i)),'td');
                    });
                   html=addShell(html,'tr');
                }
            }else if($.isArray(v)){
                //get a table
                 log('isArray');
                     var head='';
                    if(v && v[0]){
                        log('head->');
                        if($.isPlainObject( v[0] ) ){//内嵌对象数组
                            var obj={};
                            $.each(v,function(k1,v1){
                             $.each(v1,function(key,val){
                                obj[key]=null;
                             });
                            });
                            
                            $.each(obj,function(key,val){
                                head+=addShell(key,'th');
                            });
                            
                            head=addShell(head,'tr');
                            
                            $.each(v,function(key,val){
                              html+=toShow($.extend({},obj,filterKeyValue(key,val)),'tr');
                            });
                         }else {//简单数组
                             head+=addShell('val','th');
                             head=addShell(head,'tr');
                             
                             $.each(v,function(key,val){
                                html+=addShell(addShell(val,'td'),'tr');
                             });
                         }
                         
                         html=addShell(head+html,'table');
                    }
            }else{
                html=v;
            }
            
            return html;
        }
    
   
   String.prototype.lookupJson=function(fn){//不保证完全符合，但基本json还能完整个抠出
	fn = fn || function (json){console.log("jsonxxx="+json);}
	var stack=[];
	stack.peek=function(){
	//console.log("length="+this.length+",this[0]="+this[0]);
		if(this.length > 0){
			return this[this.length-1];
		}
	}
	var pair='{}[]"\'';
	var startIndex=-1;

	for(var i=0;i<this.length;i++){
		var code=this.charAt(i);
		var codePos=pair.indexOf(code);

		if(codePos < 0){
			continue;
		}
 
		var top=stack.peek();

		var topPos=pair.indexOf(top);//-1
		 // console.log('code='+code+',top='+top);
		 // console.log('codePos='+codePos+',topPos='+topPos);
		if(stack.length < 1){//
 			 stack.push(code);
 			 startIndex = i;
		}else if( codePos > 3 && (codePos-topPos) == 0 ){//"'
			// console.log("--");
			stack.pop();
		}else if( topPos > -1 && (codePos-topPos) == 1 ){//退出
			stack.pop();
			if(	stack.length < 1 &&  startIndex >-1){
				var json=this.substring(startIndex,i+1);
				fn(json);
				startIndex = -1;
			}
		}else{
			stack.push(code);
		}
 		// console.log("stack:"+stack.join());
	}

	// console.log("stack:"+stack.join());
}

       var $text =$('#text');
        var $show =$('#show');
        
        var handler=function(){
            var expr=$.trim($('#expr').val());
            var str=$text.val();
            
            var arr=[];

            
            str.lookupJson(function(jsonstr){
                arr.push(jsonstr);
            });
            
            log("jsonstr:"+arr.join(' '));
            
            if($('#merge').is(':checked')){
                log("should merge!");
                arr=['['+arr.join(',')+']']
            }
            
            
            var out=[];
          $.each(arr,function(key,val){
               log("----------:"+val);
               try{
                var json = $.parseJSON(val);
                 log(json);
                 
                  if($('#merge').is(':checked') && expr.length > 0 && $.isArray(json)){
                      var keys=expr.split('.');
                        var dd=[];
                        $.each(json,function(k,v){
                            log(k+"------"+v);
                             
                            $.each(keys,function(kk,vv){
                             log('~~~~~~~~~~~key2:'+vv);
                             if(typeof v[vv] !== 'undefined'){
                                v=v[vv];
                             }
                             }); 
                            dd.push(v);
                        });
                         
                         json=dd;
                     
                  }else{
                      if(expr.length > 0){
                         var keys=expr.split('.');
                         $.each(keys,function(val,key){
                             log('~~~~~~~~~~~~~~~~~~key:'+key);
                             if(typeof json[key] !== 'undefined'){
                                 json=json[key];
                             }
                         });
                         
                     }
                  }
                 
                out.push(toShow(json));
               }catch(e){
                   log(e);
               }
          });
          
           
          
           $show.html(out.join('<br/>'));
          
        };
       // $text.change(handler);
        $('#btn').click(handler);
        
       
       
       
   </script>
</body>

</html>